package com.derbysoft.ota.application.util;

import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.googlecode.functionalcollections.FunctionalIterables;

public abstract class Elements {
	
	public static final String OTA_NAMESPACE_URI = "http://www.opentravel.org/OTA/2003/05";

	private static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

	public static Element of(String key, String value) {
		return of(OTA_NAMESPACE_URI, key, value);
	}
	
	public static Element of(String nameSpaceUri, String key, String value) {
		return FunctionalIterables.make(of(nameSpaceUri, ImmutableMap.of(key, value))).getOnlyElement();
	}
	
	public static Collection<Element> of(final String nameSpaceUri, Map<String, String> map) {
		try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.newDocument();  
            return FunctionalIterables.make(map.entrySet()).map(
	            	new Function<Entry<String, String>, Element>() {
					public Element apply(Entry<String, String> entry) {
						Element element = document.createElementNS(nameSpaceUri, entry.getKey()); 
						element.setTextContent(entry.getValue());    
						return element;
					}
	            	}
            ).toCollection();
		} catch (ParserConfigurationException e) {
			throw Throwables.propagate(e);
		}
	}

	

}
